import { getSiteInfo } from './common'

let base = ''

const siteinfo = getSiteInfo()

function getUserid() {
  let userId = 0
  try {
    const value = uni.getStorageSync('user')
    if (value)
      userId = JSON.parse(value).userInfo.id
    return userId
  }
  catch (e) {
    return 0
  }
}

export default {
  baseOptions(params, method = 'GET') {
    const { path, data } = params
    let contentType = 'application/json'
    contentType = params.contentType || contentType
    const url = `${base}/gs_gold/${path}`
    const hasQueryParams = path.includes('?')
    const customParam = `plaid=${siteinfo.plaid}&_ajax=1`
    const separator = hasQueryParams ? '&' : '?'
    const finalUrl = url + separator + customParam
    // 这里的url我想修改一下，需要再后面添加自定义的参数，比如plaid=16，但是不清楚path是否有?xxx=xxx了，还是说没有?
    return new Promise((resolve, reject) => {
      uni.request({
        url: finalUrl, // 仅为示例，并非真实接口地址。
        data,
        method,
        header: {
          'content-type': contentType,
          'Plaid': siteinfo.plaid,
          'Appid': siteinfo.platform_appid,
          'UserId': getUserid(),
        },
        success: (res) => {
          resolve(res.data)
        },
        fail(e) {
          if (e.errNo === 21100) {
            uni.showModal({
              title: '提示',
              content: '未配置服务器域名，请到：开发-开发配置-域名管理中配置域名',
              showCancel: false,
            })
          }
          reject(e)
        },
      })
    })
  },
  get(path, data = '') {
    const option = {
      path,
      data,
    }
    return this.baseOptions(option)
  },
  post(path, data, contentType) {
    const params = {
      path,
      data,
      contentType,
    }
    return this.baseOptions(params, 'POST')
  },
  upload(filePath) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${base}/gs_gold/app.attachment/upload`,
        filePath,
        name: 'file',
        formData: {
          file: 'file',
          user: 'test',
          _ajax: 1,
        },
        header: {
          Plaid: siteinfo.plaid,
          Appid: siteinfo.platform_appid,
          UserId: getUserid(),
        },
        success: (res) => {
          resolve(JSON.parse(res.data))
        },
        fail: (e) => {
          reject(e)
        },
        complete: () => {},
      })
    })
  },
  setHost(host) {
    base = host
  },
  getHost() {
    return base
  },
}
